package com.qf.electronic.controller;


import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qf.electronic.common.R;
import com.qf.electronic.common.ResponseStatus;
import com.qf.electronic.dto.DefectTaskDto;
import com.qf.electronic.dto.DefectTaskStateDto;
import com.qf.electronic.dto.DispatchDto;
import com.qf.electronic.pojo.DefectTask;
import com.qf.electronic.pojo.User;
import com.qf.electronic.service.IDefectTaskService;
import com.qf.electronic.vo.DefectTaskVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author wu
 * @since 2023-05-04
 */
@RestController
@RequestMapping("/defectTask")
public class DefectTaskController {

    @Autowired
    private IDefectTaskService defectTaskService;

    @PreAuthorize("hasRole('ROLE_LINE')")
    @PutMapping("/dispatch")
    public R<Boolean> dispatchDefectTask(@RequestBody DispatchDto dispatchDto){
        UpdateWrapper<DefectTask> wrapper = new UpdateWrapper<>();
        wrapper.set("defect_user", dispatchDto.getOperationUser());
        wrapper.set("state", 1);
        wrapper.eq("id", dispatchDto.getId());
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        User user = (User) authentication.getPrincipal();
        wrapper.eq("created_user", user.getUsername());
        return R.ok(defectTaskService.update(wrapper));
    }

    @PutMapping
    public R<Boolean> updateDefectTask(@Valid @RequestBody DefectTask defectTask, BindingResult result){
        if(result.hasFieldErrors()){
            return R.error(ResponseStatus.INVALID_PARAMETER);
        }
        Integer state = defectTask.getState();
        if(state > 0){
            return R.error(ResponseStatus.ILLEGAL_DATA_STATE);
        }
        return R.ok(defectTaskService.updateById(defectTask));
    }

    @PutMapping("/state")
    public R<Boolean> updateDefectTaskState(@RequestBody DefectTaskStateDto stateDto){
        UpdateWrapper<DefectTask> wrapper =new UpdateWrapper<>();
        wrapper.set("state", stateDto.getState());
        wrapper.eq("id", stateDto.getId());
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        User user = (User) authentication.getPrincipal();
        wrapper.eq("defect_user", user.getUsername());
        return R.ok(defectTaskService.update(wrapper));
    }

    @GetMapping
    public R<Page<DefectTaskVo>> searchDefectTask(DefectTaskDto taskDto){
        return R.ok(defectTaskService.getDefectTasks(taskDto));
    }
}

